1 //
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/aosp/dynamic_partition_control_android.h"
18
19 #include <algorithm>
20 #include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
21 #include <cstdint>
22 #include <map>
23 #include <memory>
24 #include <set>
25 #include <string>
26 #include <string_view>
27 #include <utility>
28 #include <vector>
29
30 #include <android-base/properties.h>
31 #include <android-base/strings.h>
32 #include <base/files/file_util.h>
33 #include <base/logging.h>
34 #include <base/strings/string_util.h>
35 #include <base/strings/stringprintf.h>
36 #include <bootloader_message/bootloader_message.h>
37 #include <fs_mgr.h>
38 #include <fs_mgr_dm_linear.h>
39 #include <fs_mgr_overlayfs.h>
40 #include <libavb/libavb.h>
41 #include <libdm/dm.h>
42 #include <liblp/liblp.h>
43 #include <libsnapshot/cow_writer.h>
44 #include <libsnapshot/snapshot.h>
45 #include <libsnapshot/snapshot_stub.h>
46
47 #include "update_engine/aosp/cleanup_previous_update_action.h"
48 #include "update_engine/aosp/dynamic_partition_utils.h"
49 #include "update_engine/common/boot_control_interface.h"
50 #include "update_engine/common/dynamic_partition_control_interface.h"
51 #include "update_engine/common/platform_constants.h"
52 #include "update_engine/common/utils.h"
53 #include "update_engine/payload_consumer/cow_writer_file_descriptor.h"
54 #include "update_engine/payload_consumer/delta_performer.h"
55
56 using android::base::GetBoolProperty;
57 using android::base::GetProperty;
58 using android::base::Join;
59 using android::dm::DeviceMapper;
60 using android::dm::DmDeviceState;
61 using android::fs_mgr::CreateLogicalPartition;
62 using android::fs_mgr::CreateLogicalPartitionParams;
63 using android::fs_mgr::DestroyLogicalPartition;
64 using android::fs_mgr::Fstab;
65 using android::fs_mgr::MetadataBuilder;
66 using android::fs_mgr::Partition;
67 using android::fs_mgr::PartitionOpener;
68 using android::fs_mgr::SlotSuffixForSlotNumber;
69 using android::snapshot::OptimizeSourceCopyOperation;
70 using android::snapshot::Return;
71 using android::snapshot::SnapshotManager;
72 using android::snapshot::SnapshotManagerStub;
73 using android::snapshot::UpdateState;
74 using base::StringPrintf;
75
76 namespace chromeos_update_engine {
77
78 constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
79 constexpr char kRetrfoitDynamicPartitions[] =
80 "ro.boot.dynamic_partitions_retrofit";
81 constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
82 constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
83 constexpr char kVirtualAbCompressionEnabled[] =
84 "ro.virtual_ab.compression.enabled";
85 constexpr auto&& kVirtualAbCompressionXorEnabled =
86 "ro.virtual_ab.compression.xor.enabled";
87
88 // Currently, android doesn't have a retrofit prop for VAB Compression. However,
89 // struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
90 // is here just to simplify code. Replace it with real retrofit prop name once
91 // there is one.
92 constexpr char kVirtualAbCompressionRetrofit[] = "";
93 constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
94 // Map timeout for dynamic partitions.
95 constexpr std::chrono::milliseconds kMapTimeout{1000};
96 // Map timeout for dynamic partitions with snapshots. Since several devices
97 // needs to be mapped, this timeout is longer than |kMapTimeout|.
98 constexpr std::chrono::milliseconds kMapSnapshotTimeout{10000};
99
~DynamicPartitionControlAndroid()100 DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
101 UnmapAllPartitions();
102 metadata_device_.reset();
103 }
104
GetFeatureFlag(const char * enable_prop,const char * retrofit_prop)105 static FeatureFlag GetFeatureFlag(const char* enable_prop,
106 const char* retrofit_prop) {
107 // Default retrofit to false if retrofit_prop is empty.
108 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
109 GetBoolProperty(retrofit_prop, false);
110 bool enabled = GetBoolProperty(enable_prop, false);
111 if (retrofit && !enabled) {
112 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
113 << " is not. These sysprops are inconsistent. Assume that "
114 << enable_prop << " is true from now on.";
115 }
116 if (retrofit) {
117 return FeatureFlag(FeatureFlag::Value::RETROFIT);
118 }
119 if (enabled) {
120 return FeatureFlag(FeatureFlag::Value::LAUNCH);
121 }
122 return FeatureFlag(FeatureFlag::Value::NONE);
123 }
124
DynamicPartitionControlAndroid(uint32_t source_slot)125 DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
126 uint32_t source_slot)
127 : dynamic_partitions_(
128 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
129 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
130 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
131 kVirtualAbCompressionRetrofit)),
132 virtual_ab_compression_xor_(
133 GetFeatureFlag(kVirtualAbCompressionXorEnabled, "")),
134 source_slot_(source_slot) {
135 if (GetVirtualAbFeatureFlag().IsEnabled()) {
136 snapshot_ = SnapshotManager::New();
137 } else {
138 snapshot_ = SnapshotManagerStub::New();
139 }
140 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
141 }
142
GetDynamicPartitionsFeatureFlag()143 FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
144 return dynamic_partitions_;
145 }
146
GetVirtualAbFeatureFlag()147 FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
148 return virtual_ab_;
149 }
150
151 FeatureFlag
GetVirtualAbCompressionFeatureFlag()152 DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
153 if constexpr (constants::kIsRecovery) {
154 // Don't attempt VABC in recovery
155 return FeatureFlag(FeatureFlag::Value::NONE);
156 }
157 return virtual_ab_compression_;
158 }
159
160 FeatureFlag
GetVirtualAbCompressionXorFeatureFlag()161 DynamicPartitionControlAndroid::GetVirtualAbCompressionXorFeatureFlag() {
162 return virtual_ab_compression_xor_;
163 }
164
OptimizeOperation(const std::string & partition_name,const InstallOperation & operation,InstallOperation * optimized)165 bool DynamicPartitionControlAndroid::OptimizeOperation(
166 const std::string& partition_name,
167 const InstallOperation& operation,
168 InstallOperation* optimized) {
169 switch (operation.type()) {
170 case InstallOperation::SOURCE_COPY:
171 return target_supports_snapshot_ &&
172 GetVirtualAbFeatureFlag().IsEnabled() &&
173 mapped_devices_.count(partition_name +
174 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
175 OptimizeSourceCopyOperation(operation, optimized);
176 break;
177 default:
178 break;
179 }
180 return false;
181 }
182
MapPartitionInternal(const std::string & super_device,const std::string & target_partition_name,uint32_t slot,bool force_writable,std::string * path)183 bool DynamicPartitionControlAndroid::MapPartitionInternal(
184 const std::string& super_device,
185 const std::string& target_partition_name,
186 uint32_t slot,
187 bool force_writable,
188 std::string* path) {
189 CreateLogicalPartitionParams params = {
190 .block_device = super_device,
191 .metadata_slot = slot,
192 .partition_name = target_partition_name,
193 .force_writable = force_writable,
194 };
195 bool success = false;
196 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
197 force_writable && ExpectMetadataMounted()) {
198 // Only target partitions are mapped with force_writable. On Virtual
199 // A/B devices, target partitions may overlap with source partitions, so
200 // they must be mapped with snapshot.
201 // One exception is when /metadata is not mounted. Fallback to
202 // CreateLogicalPartition as snapshots are not created in the first place.
203 params.timeout_ms = kMapSnapshotTimeout;
204 success = snapshot_->MapUpdateSnapshot(params, path);
205 } else {
206 params.timeout_ms = kMapTimeout;
207 success = CreateLogicalPartition(params, path);
208 }
209
210 if (!success) {
211 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
212 << super_device << " on device mapper.";
213 return false;
214 }
215 LOG(INFO) << "Succesfully mapped " << target_partition_name
216 << " to device mapper (force_writable = " << force_writable
217 << "); device path at " << *path;
218 mapped_devices_.insert(target_partition_name);
219 return true;
220 }
221
MapPartitionOnDeviceMapper(const std::string & super_device,const std::string & target_partition_name,uint32_t slot,bool force_writable,std::string * path)222 bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
223 const std::string& super_device,
224 const std::string& target_partition_name,
225 uint32_t slot,
226 bool force_writable,
227 std::string* path) {
228 DmDeviceState state = GetState(target_partition_name);
229 if (state == DmDeviceState::ACTIVE) {
230 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
231 if (GetDmDevicePathByName(target_partition_name, path)) {
232 LOG(INFO) << target_partition_name
233 << " is mapped on device mapper: " << *path;
234 return true;
235 }
236 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
237 return false;
238 }
239 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
240 // the device might be mapped incorrectly before. Attempt to unmap it.
241 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
242 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
243 // should directly call GetDmDevicePathByName.
244 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
245 LOG(ERROR) << target_partition_name
246 << " is mapped before the update, and it cannot be unmapped.";
247 return false;
248 }
249 state = GetState(target_partition_name);
250 if (state != DmDeviceState::INVALID) {
251 LOG(ERROR) << target_partition_name << " is unmapped but state is "
252 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
253 return false;
254 }
255 }
256 if (state == DmDeviceState::INVALID) {
257 return MapPartitionInternal(
258 super_device, target_partition_name, slot, force_writable, path);
259 }
260
261 LOG(ERROR) << target_partition_name
262 << " is mapped on device mapper but state is unknown: "
263 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
264 return false;
265 }
266
UnmapPartitionOnDeviceMapper(const std::string & target_partition_name)267 bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
268 const std::string& target_partition_name) {
269 if (DeviceMapper::Instance().GetState(target_partition_name) !=
270 DmDeviceState::INVALID) {
271 // Partitions at target slot on non-Virtual A/B devices are mapped as
272 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
273 // preopt apps as dm-linear.
274 // Call DestroyLogicalPartition to handle these cases.
275 bool success = DestroyLogicalPartition(target_partition_name);
276
277 // On a Virtual A/B device, |target_partition_name| may be a leftover from
278 // a paused update. Clean up any underlying devices.
279 if (ExpectMetadataMounted()) {
280 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
281 } else {
282 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
283 << ") because metadata is not mounted";
284 }
285
286 if (!success) {
287 LOG(ERROR) << "Cannot unmap " << target_partition_name
288 << " from device mapper.";
289 return false;
290 }
291 LOG(INFO) << "Successfully unmapped " << target_partition_name
292 << " from device mapper.";
293 }
294 mapped_devices_.erase(target_partition_name);
295 return true;
296 }
297
UnmapAllPartitions()298 bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
299 snapshot_->UnmapAllSnapshots();
300 if (mapped_devices_.empty()) {
301 return false;
302 }
303 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
304 // a copy is needed for the loop.
305 std::set<std::string> mapped = mapped_devices_;
306 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
307 for (const auto& partition_name : mapped) {
308 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
309 }
310 return true;
311 }
312
Cleanup()313 void DynamicPartitionControlAndroid::Cleanup() {
314 UnmapAllPartitions();
315 metadata_device_.reset();
316 if (GetVirtualAbFeatureFlag().IsEnabled()) {
317 snapshot_ = SnapshotManager::New();
318 } else {
319 snapshot_ = SnapshotManagerStub::New();
320 }
321 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
322 }
323
DeviceExists(const std::string & path)324 bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
325 return base::PathExists(base::FilePath(path));
326 }
327
GetState(const std::string & name)328 android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
329 const std::string& name) {
330 return DeviceMapper::Instance().GetState(name);
331 }
332
GetDmDevicePathByName(const std::string & name,std::string * path)333 bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
334 const std::string& name, std::string* path) {
335 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
336 }
337
338 std::unique_ptr<MetadataBuilder>
LoadMetadataBuilder(const std::string & super_device,uint32_t slot)339 DynamicPartitionControlAndroid::LoadMetadataBuilder(
340 const std::string& super_device, uint32_t slot) {
341 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
342 if (builder == nullptr) {
343 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
344 << " in " << super_device;
345 return nullptr;
346 }
347 LOG(INFO) << "Loaded metadata from slot "
348 << BootControlInterface::SlotName(slot) << " in " << super_device;
349 return builder;
350 }
351
352 std::unique_ptr<MetadataBuilder>
LoadMetadataBuilder(const std::string & super_device,uint32_t source_slot,uint32_t target_slot)353 DynamicPartitionControlAndroid::LoadMetadataBuilder(
354 const std::string& super_device,
355 uint32_t source_slot,
356 uint32_t target_slot) {
357 bool always_keep_source_slot = !target_supports_snapshot_;
358 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
359 super_device,
360 source_slot,
361 target_slot,
362 always_keep_source_slot);
363 if (builder == nullptr) {
364 LOG(WARNING) << "No metadata slot "
365 << BootControlInterface::SlotName(source_slot) << " in "
366 << super_device;
367 return nullptr;
368 }
369 LOG(INFO) << "Created metadata for new update from slot "
370 << BootControlInterface::SlotName(source_slot) << " in "
371 << super_device;
372 return builder;
373 }
374
StoreMetadata(const std::string & super_device,MetadataBuilder * builder,uint32_t target_slot)375 bool DynamicPartitionControlAndroid::StoreMetadata(
376 const std::string& super_device,
377 MetadataBuilder* builder,
378 uint32_t target_slot) {
379 auto metadata = builder->Export();
380 if (metadata == nullptr) {
381 LOG(ERROR) << "Cannot export metadata to slot "
382 << BootControlInterface::SlotName(target_slot) << " in "
383 << super_device;
384 return false;
385 }
386
387 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
388 if (!FlashPartitionTable(super_device, *metadata)) {
389 LOG(ERROR) << "Cannot write metadata to " << super_device;
390 return false;
391 }
392 LOG(INFO) << "Written metadata to " << super_device;
393 } else {
394 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
395 LOG(ERROR) << "Cannot write metadata to slot "
396 << BootControlInterface::SlotName(target_slot) << " in "
397 << super_device;
398 return false;
399 }
400 LOG(INFO) << "Copied metadata to slot "
401 << BootControlInterface::SlotName(target_slot) << " in "
402 << super_device;
403 }
404
405 return true;
406 }
407
GetDeviceDir(std::string * out)408 bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
409 // We can't use fs_mgr to look up |partition_name| because fstab
410 // doesn't list every slot partition (it uses the slotselect option
411 // to mask the suffix).
412 //
413 // We can however assume that there's an entry for the /misc mount
414 // point and use that to get the device file for the misc
415 // partition. This helps us locate the disk that |partition_name|
416 // resides on. From there we'll assume that a by-name scheme is used
417 // so we can just replace the trailing "misc" by the given
418 // |partition_name| and suffix corresponding to |slot|, e.g.
419 //
420 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
421 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
422 //
423 // If needed, it's possible to relax the by-name assumption in the
424 // future by trawling /sys/block looking for the appropriate sibling
425 // of misc and then finding an entry in /dev matching the sysfs
426 // entry.
427
428 std::string err, misc_device = get_bootloader_message_blk_device(&err);
429 if (misc_device.empty()) {
430 LOG(ERROR) << "Unable to get misc block device: " << err;
431 return false;
432 }
433
434 if (!utils::IsSymlink(misc_device.c_str())) {
435 LOG(ERROR) << "Device file " << misc_device << " for /misc "
436 << "is not a symlink.";
437 return false;
438 }
439 *out = base::FilePath(misc_device).DirName().value();
440 return true;
441 }
442
PreparePartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,bool update,uint64_t * required_size)443 bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
444 uint32_t source_slot,
445 uint32_t target_slot,
446 const DeltaArchiveManifest& manifest,
447 bool update,
448 uint64_t* required_size) {
449 source_slot_ = source_slot;
450 target_slot_ = target_slot;
451 if (required_size != nullptr) {
452 *required_size = 0;
453 }
454
455 if (fs_mgr_overlayfs_is_setup()) {
456 // Non DAP devices can use overlayfs as well.
457 LOG(WARNING)
458 << "overlayfs overrides are active and can interfere with our "
459 "resources.\n"
460 << "run adb enable-verity to deactivate if required and try again.";
461 }
462
463 // If metadata is erased but not formatted, it is possible to not mount
464 // it in recovery. It is acceptable to skip mounting and choose fallback path
465 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
466 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
467
468 if (update) {
469 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
470 }
471
472 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
473 return true;
474 }
475
476 if (target_slot == source_slot) {
477 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
478 return false;
479 }
480
481 if (!SetTargetBuildVars(manifest)) {
482 return false;
483 }
484 for (auto& list : dynamic_partition_list_) {
485 list.clear();
486 }
487
488 // Although the current build supports dynamic partitions, the given payload
489 // doesn't use it for target partitions. This could happen when applying a
490 // retrofit update. Skip updating the partition metadata for the target slot.
491 if (!is_target_dynamic_) {
492 return true;
493 }
494
495 if (!update)
496 return true;
497
498 bool delete_source = false;
499
500 if (GetVirtualAbFeatureFlag().IsEnabled()) {
501 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
502 // called before calling UnmapUpdateSnapshot.
503 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
504 // calls BeginUpdate() which resets update state
505 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
506 // failed in recovery, explicitly CancelUpdate().
507 if (target_supports_snapshot_) {
508 if (PrepareSnapshotPartitionsForUpdate(
509 source_slot, target_slot, manifest, required_size)) {
510 return true;
511 }
512
513 // Virtual A/B device doing Virtual A/B update in Android mode must use
514 // snapshots.
515 if (!IsRecovery()) {
516 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
517 << "mode";
518 return false;
519 }
520
521 delete_source = true;
522 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
523 << "Attempt to overwrite existing partitions if possible";
524 } else {
525 // Downgrading to an non-Virtual A/B build or is secondary OTA.
526 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
527 << "snapshots.";
528 }
529
530 // In recovery, if /metadata is not mounted, it is likely that metadata
531 // partition is erased and not formatted yet. After sideloading, when
532 // rebooting into the new version, init will erase metadata partition,
533 // hence the failure of CancelUpdate() can be ignored here.
534 // However, if metadata is mounted and CancelUpdate fails, sideloading
535 // should not proceed because during next boot, snapshots will overlay on
536 // the devices incorrectly.
537 if (ExpectMetadataMounted()) {
538 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
539 } else {
540 LOG(INFO) << "Skip canceling previous update because metadata is not "
541 << "mounted";
542 }
543 }
544
545 // TODO(xunchang) support partial update on non VAB enabled devices.
546 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
547 source_slot, target_slot, manifest, delete_source));
548
549 if (required_size != nullptr) {
550 *required_size = 0;
551 }
552 return true;
553 }
554
SetTargetBuildVars(const DeltaArchiveManifest & manifest)555 bool DynamicPartitionControlAndroid::SetTargetBuildVars(
556 const DeltaArchiveManifest& manifest) {
557 // Precondition: current build supports dynamic partition.
558 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
559
560 bool is_target_dynamic =
561 !manifest.dynamic_partition_metadata().groups().empty();
562 bool target_supports_snapshot =
563 manifest.dynamic_partition_metadata().snapshot_enabled();
564
565 if (manifest.partial_update()) {
566 // Partial updates requires DAP. On partial updates that does not involve
567 // dynamic partitions, groups() can be empty, so also assume
568 // is_target_dynamic in this case. This assumption should be safe because we
569 // also check target_supports_snapshot below, which presumably also implies
570 // target build supports dynamic partition.
571 if (!is_target_dynamic) {
572 LOG(INFO) << "Assuming target build supports dynamic partitions for "
573 "partial updates.";
574 is_target_dynamic = true;
575 }
576
577 // Partial updates requires Virtual A/B. Double check that both current
578 // build and target build supports Virtual A/B.
579 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
580 LOG(ERROR) << "Partial update cannot be applied on a device that does "
581 "not support snapshots.";
582 return false;
583 }
584 if (!target_supports_snapshot) {
585 LOG(ERROR) << "Cannot apply partial update to a build that does not "
586 "support snapshots.";
587 return false;
588 }
589 }
590
591 // Store the flags.
592 is_target_dynamic_ = is_target_dynamic;
593 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
594 // snapshots would not work without dynamic partition.
595 if (is_target_dynamic_) {
596 target_supports_snapshot_ = target_supports_snapshot;
597 }
598 return true;
599 }
600
601 namespace {
602 // Try our best to erase AVB footer.
603 class AvbFooterEraser {
604 public:
AvbFooterEraser(const std::string & path)605 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
Erase()606 bool Erase() {
607 // Try to mark the block device read-only. Ignore any
608 // failure since this won't work when passing regular files.
609 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
610
611 fd_.reset(new EintrSafeFileDescriptor());
612 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
613 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
614
615 // Need to write end-AVB_FOOTER_SIZE to end.
616 static_assert(AVB_FOOTER_SIZE > 0);
617 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
618 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
619 uint64_t write_size = AVB_FOOTER_SIZE;
620 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
621 << (offset + write_size) << "] (" << write_size << " bytes)";
622 brillo::Blob zeros(write_size);
623 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
624 return true;
625 }
~AvbFooterEraser()626 ~AvbFooterEraser() {
627 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
628 if (!fd_->Close()) {
629 LOG(WARNING) << "Failed to close fd for " << path_;
630 }
631 }
632
633 private:
634 std::string path_;
635 FileDescriptorPtr fd_;
636 };
637
638 } // namespace
639
640 std::optional<bool>
IsAvbEnabledOnSystemOther()641 DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
642 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
643 if (prefix.empty()) {
644 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
645 return std::nullopt;
646 }
647 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
648 return IsAvbEnabledInFstab(path);
649 }
650
IsAvbEnabledInFstab(const std::string & path)651 std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
652 const std::string& path) {
653 Fstab fstab;
654 if (!ReadFstabFromFile(path, &fstab)) {
655 PLOG(WARNING) << "Cannot read fstab from " << path;
656 if (errno == ENOENT) {
657 return false;
658 }
659 return std::nullopt;
660 }
661 for (const auto& entry : fstab) {
662 if (!entry.avb_keys.empty()) {
663 return true;
664 }
665 }
666 return false;
667 }
668
GetSystemOtherPath(uint32_t source_slot,uint32_t target_slot,const std::string & partition_name_suffix,std::string * path,bool * should_unmap)669 bool DynamicPartitionControlAndroid::GetSystemOtherPath(
670 uint32_t source_slot,
671 uint32_t target_slot,
672 const std::string& partition_name_suffix,
673 std::string* path,
674 bool* should_unmap) {
675 path->clear();
676 *should_unmap = false;
677
678 // Check that AVB is enabled on system_other before erasing.
679 auto has_avb = IsAvbEnabledOnSystemOther();
680 TEST_AND_RETURN_FALSE(has_avb.has_value());
681 if (!has_avb.value()) {
682 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
683 return true;
684 }
685
686 if (!IsRecovery()) {
687 // Found unexpected avb_keys for system_other on devices retrofitting
688 // dynamic partitions. Previous crash in update_engine may leave logical
689 // partitions mapped on physical system_other partition. It is difficult to
690 // handle these cases. Just fail.
691 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
692 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
693 << "retrofit dynamic partitions. They should not have AVB "
694 << "enabled on system_other.";
695 return false;
696 }
697 }
698
699 std::string device_dir_str;
700 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
701 base::FilePath device_dir(device_dir_str);
702
703 // On devices without dynamic partition, search for static partitions.
704 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
705 *path = device_dir.Append(partition_name_suffix).value();
706 TEST_AND_RETURN_FALSE(DeviceExists(*path));
707 return true;
708 }
709
710 auto source_super_device =
711 device_dir.Append(GetSuperPartitionName(source_slot)).value();
712
713 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
714 if (builder == nullptr) {
715 if (IsRecovery()) {
716 // It might be corrupted for some reason. It should still be able to
717 // sideload.
718 LOG(WARNING) << "Super partition metadata cannot be read from the source "
719 << "slot, skip erasing.";
720 return true;
721 } else {
722 // Device has booted into Android mode, indicating that the super
723 // partition metadata should be there.
724 LOG(ERROR) << "Super partition metadata cannot be read from the source "
725 << "slot. This is unexpected on devices with dynamic "
726 << "partitions enabled.";
727 return false;
728 }
729 }
730 auto p = builder->FindPartition(partition_name_suffix);
731 if (p == nullptr) {
732 // If the source slot is flashed without system_other, it does not exist
733 // in super partition metadata at source slot. It is safe to skip it.
734 LOG(INFO) << "Can't find " << partition_name_suffix
735 << " in metadata source slot, skip erasing.";
736 return true;
737 }
738 // System_other created by flashing tools should be erased.
739 // If partition is created by update_engine (via NewForUpdate), it is a
740 // left-over partition from the previous update and does not contain
741 // system_other, hence there is no need to erase.
742 // Note the reverse is not necessary true. If the flag is not set, we don't
743 // know if the partition is created by update_engine or by flashing tools
744 // because older versions of super partition metadata does not contain this
745 // flag. It is okay to erase the AVB footer anyways.
746 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
747 LOG(INFO) << partition_name_suffix
748 << " does not contain system_other, skip erasing.";
749 return true;
750 }
751
752 if (p->size() < AVB_FOOTER_SIZE) {
753 LOG(INFO) << partition_name_suffix << " has length " << p->size()
754 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
755 << "), skip erasing.";
756 return true;
757 }
758
759 // Delete any pre-existing device with name |partition_name_suffix| and
760 // also remove it from |mapped_devices_|.
761 // In recovery, metadata might not be mounted, and
762 // UnmapPartitionOnDeviceMapper might fail. However,
763 // it is unusual that system_other has already been mapped. Hence, just skip.
764 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
765 // Use CreateLogicalPartition directly to avoid mapping with existing
766 // snapshots.
767 CreateLogicalPartitionParams params = {
768 .block_device = source_super_device,
769 .metadata_slot = source_slot,
770 .partition_name = partition_name_suffix,
771 .force_writable = true,
772 .timeout_ms = kMapTimeout,
773 };
774 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
775 *should_unmap = true;
776 return true;
777 }
778
EraseSystemOtherAvbFooter(uint32_t source_slot,uint32_t target_slot)779 bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
780 uint32_t source_slot, uint32_t target_slot) {
781 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
782
783 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
784 const std::string partition_name_suffix = "system" + target_suffix;
785
786 std::string path;
787 bool should_unmap = false;
788
789 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
790 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
791
792 if (path.empty()) {
793 return true;
794 }
795
796 bool ret = AvbFooterEraser(path).Erase();
797
798 // Delete |partition_name_suffix| from device mapper and from
799 // |mapped_devices_| again so that it does not interfere with update process.
800 // In recovery, metadata might not be mounted, and
801 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
802 // should be called. If DestroyLogicalPartition does fail, it is still okay
803 // to skip the error here and let Prepare*() fail later.
804 if (should_unmap) {
805 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
806 }
807
808 return ret;
809 }
810
PrepareDynamicPartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,bool delete_source)811 bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
812 uint32_t source_slot,
813 uint32_t target_slot,
814 const DeltaArchiveManifest& manifest,
815 bool delete_source) {
816 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
817
818 // Unmap all the target dynamic partitions because they would become
819 // inconsistent with the new metadata.
820 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
821 for (const auto& partition_name : group.partition_names()) {
822 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
823 return false;
824 }
825 }
826 }
827
828 std::string device_dir_str;
829 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
830 base::FilePath device_dir(device_dir_str);
831 auto source_device =
832 device_dir.Append(GetSuperPartitionName(source_slot)).value();
833
834 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
835 if (builder == nullptr) {
836 LOG(ERROR) << "No metadata at "
837 << BootControlInterface::SlotName(source_slot);
838 return false;
839 }
840
841 if (delete_source) {
842 TEST_AND_RETURN_FALSE(
843 DeleteSourcePartitions(builder.get(), source_slot, manifest));
844 }
845
846 TEST_AND_RETURN_FALSE(
847 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
848
849 auto target_device =
850 device_dir.Append(GetSuperPartitionName(target_slot)).value();
851 return StoreMetadata(target_device, builder.get(), target_slot);
852 }
853
854 DynamicPartitionControlAndroid::SpaceLimit
GetSpaceLimit(bool use_snapshot)855 DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
856 // On device retrofitting dynamic partitions, allocatable_space = "super",
857 // where "super" is the sum of all block devices for that slot. Since block
858 // devices are dedicated for the corresponding slot, there's no need to halve
859 // the allocatable space.
860 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
861 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
862
863 // On device launching dynamic partitions w/o VAB, regardless of recovery
864 // sideload, super partition must be big enough to hold both A and B slots of
865 // groups. Hence,
866 // allocatable_space = super / 2
867 if (!GetVirtualAbFeatureFlag().IsEnabled())
868 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
869
870 // Source build supports VAB. Super partition must be big enough to hold
871 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
872 // where additional warning messages needs to be written.
873
874 // If using snapshot updates, implying that target build also uses VAB,
875 // allocatable_space = super
876 if (use_snapshot)
877 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
878
879 // Source build supports VAB but not using snapshot updates. There are
880 // several cases, as listed below.
881 // Sideloading: allocatable_space = super.
882 if (IsRecovery())
883 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
884
885 // On launch VAB device, this implies secondary payload.
886 // Technically, we don't have to check anything, but sum(groups) < super
887 // still applies.
888 if (!GetVirtualAbFeatureFlag().IsRetrofit())
889 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
890
891 // On retrofit VAB device, either of the following:
892 // - downgrading: allocatable_space = super / 2
893 // - secondary payload: don't check anything
894 // These two cases are indistinguishable,
895 // hence emit warning if sum(groups) > super / 2
896 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
897 }
898
CheckSuperPartitionAllocatableSpace(android::fs_mgr::MetadataBuilder * builder,const DeltaArchiveManifest & manifest,bool use_snapshot)899 bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
900 android::fs_mgr::MetadataBuilder* builder,
901 const DeltaArchiveManifest& manifest,
902 bool use_snapshot) {
903 uint64_t sum_groups = 0;
904 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
905 sum_groups += group.size();
906 }
907
908 uint64_t full_space = builder->AllocatableSpace();
909 uint64_t half_space = full_space / 2;
910 constexpr const char* fmt =
911 "The maximum size of all groups for the target slot (%" PRIu64
912 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
913 switch (GetSpaceLimit(use_snapshot)) {
914 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
915 if (sum_groups > half_space) {
916 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
917 return false;
918 }
919 // If test passes, it implies that the following two conditions also pass.
920 break;
921 }
922 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
923 if (sum_groups > half_space) {
924 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
925 << " This is allowed for downgrade or secondary OTA on "
926 "retrofit VAB device.";
927 }
928 // still check sum(groups) < super
929 [[fallthrough]];
930 }
931 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
932 if (sum_groups > full_space) {
933 LOG(ERROR) << base::StringPrintf(fmt, sum_groups, "", full_space);
934 return false;
935 }
936 break;
937 }
938 }
939
940 return true;
941 }
942
PrepareSnapshotPartitionsForUpdate(uint32_t source_slot,uint32_t target_slot,const DeltaArchiveManifest & manifest,uint64_t * required_size)943 bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
944 uint32_t source_slot,
945 uint32_t target_slot,
946 const DeltaArchiveManifest& manifest,
947 uint64_t* required_size) {
948 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
949
950 std::string device_dir_str;
951 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
952 base::FilePath device_dir(device_dir_str);
953 auto super_device =
954 device_dir.Append(GetSuperPartitionName(source_slot)).value();
955 auto builder = LoadMetadataBuilder(super_device, source_slot);
956 if (builder == nullptr) {
957 LOG(ERROR) << "No metadata at "
958 << BootControlInterface::SlotName(source_slot);
959 return false;
960 }
961
962 TEST_AND_RETURN_FALSE(
963 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
964
965 if (!snapshot_->BeginUpdate()) {
966 LOG(ERROR) << "Cannot begin new update.";
967 return false;
968 }
969 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
970 if (!ret) {
971 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
972 if (required_size != nullptr &&
973 ret.error_code() == Return::ErrorCode::NO_SPACE) {
974 *required_size = ret.required_size();
975 }
976 return false;
977 }
978 return true;
979 }
980
GetSuperPartitionName(uint32_t slot)981 std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
982 uint32_t slot) {
983 return fs_mgr_get_super_partition_name(slot);
984 }
985
UpdatePartitionMetadata(MetadataBuilder * builder,uint32_t target_slot,const DeltaArchiveManifest & manifest)986 bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
987 MetadataBuilder* builder,
988 uint32_t target_slot,
989 const DeltaArchiveManifest& manifest) {
990 // Check preconditions.
991 if (GetVirtualAbFeatureFlag().IsEnabled()) {
992 CHECK(!target_supports_snapshot_ || IsRecovery())
993 << "Must use snapshot on VAB device when target build supports VAB and "
994 "not sideloading.";
995 LOG_IF(INFO, !target_supports_snapshot_)
996 << "Not using snapshot on VAB device because target build does not "
997 "support snapshot. Secondary or downgrade OTA?";
998 LOG_IF(INFO, IsRecovery())
999 << "Not using snapshot on VAB device because sideloading.";
1000 }
1001
1002 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1003 // COW group needs to be deleted to ensure there are enough space to create
1004 // target partitions.
1005 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1006
1007 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1008 DeleteGroupsWithSuffix(builder, target_suffix);
1009
1010 TEST_AND_RETURN_FALSE(
1011 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
1012
1013 // name of partition(e.g. "system") -> size in bytes
1014 std::map<std::string, uint64_t> partition_sizes;
1015 for (const auto& partition : manifest.partitions()) {
1016 partition_sizes.emplace(partition.partition_name(),
1017 partition.new_partition_info().size());
1018 }
1019
1020 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1021 auto group_name_suffix = group.name() + target_suffix;
1022 if (!builder->AddGroup(group_name_suffix, group.size())) {
1023 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
1024 << group.size();
1025 return false;
1026 }
1027 LOG(INFO) << "Added group " << group_name_suffix << " with size "
1028 << group.size();
1029
1030 for (const auto& partition_name : group.partition_names()) {
1031 auto partition_sizes_it = partition_sizes.find(partition_name);
1032 if (partition_sizes_it == partition_sizes.end()) {
1033 // TODO(tbao): Support auto-filling partition info for framework-only
1034 // OTA.
1035 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1036 << partition_name << " but it is not part of the manifest. "
1037 << "This is not supported.";
1038 return false;
1039 }
1040 uint64_t partition_size = partition_sizes_it->second;
1041
1042 auto partition_name_suffix = partition_name + target_suffix;
1043 Partition* p = builder->AddPartition(
1044 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1045 if (!p) {
1046 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1047 << " to group " << group_name_suffix;
1048 return false;
1049 }
1050 if (!builder->ResizePartition(p, partition_size)) {
1051 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
1052 << " to size " << partition_size << ". Not enough space?";
1053 return false;
1054 }
1055 if (p->size() < partition_size) {
1056 LOG(ERROR) << "Partition " << partition_name_suffix
1057 << " was expected to have size " << partition_size
1058 << ", but instead has size " << p->size();
1059 return false;
1060 }
1061 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
1062 << group_name_suffix << " with size " << partition_size;
1063 }
1064 }
1065
1066 return true;
1067 }
1068
FinishUpdate(bool powerwash_required)1069 bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
1070 if (ExpectMetadataMounted()) {
1071 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1072 LOG(INFO) << "Snapshot writes are done.";
1073 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1074 }
1075 } else {
1076 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1077 << "mounted";
1078 }
1079 return true;
1080 }
1081
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,bool not_in_payload,std::string * device,bool * is_dynamic)1082 bool DynamicPartitionControlAndroid::GetPartitionDevice(
1083 const std::string& partition_name,
1084 uint32_t slot,
1085 uint32_t current_slot,
1086 bool not_in_payload,
1087 std::string* device,
1088 bool* is_dynamic) {
1089 auto partition_dev =
1090 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
1091 if (!partition_dev.has_value()) {
1092 return false;
1093 }
1094 if (device) {
1095 *device = std::move(partition_dev->rw_device_path);
1096 }
1097 if (is_dynamic) {
1098 *is_dynamic = partition_dev->is_dynamic;
1099 }
1100 return true;
1101 }
1102
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,std::string * device)1103 bool DynamicPartitionControlAndroid::GetPartitionDevice(
1104 const std::string& partition_name,
1105 uint32_t slot,
1106 uint32_t current_slot,
1107 std::string* device) {
1108 return GetPartitionDevice(
1109 partition_name, slot, current_slot, false, device, nullptr);
1110 }
1111
GetStaticDevicePath(const base::FilePath & device_dir,const std::string & partition_name_suffixed)1112 static std::string GetStaticDevicePath(
1113 const base::FilePath& device_dir,
1114 const std::string& partition_name_suffixed) {
1115 base::FilePath path = device_dir.Append(partition_name_suffixed);
1116 return path.value();
1117 }
1118
1119 std::optional<PartitionDevice>
GetPartitionDevice(const std::string & partition_name,uint32_t slot,uint32_t current_slot,bool not_in_payload)1120 DynamicPartitionControlAndroid::GetPartitionDevice(
1121 const std::string& partition_name,
1122 uint32_t slot,
1123 uint32_t current_slot,
1124 bool not_in_payload) {
1125 std::string device_dir_str;
1126 if (!GetDeviceDir(&device_dir_str)) {
1127 LOG(ERROR) << "Failed to GetDeviceDir()";
1128 return {};
1129 }
1130 const base::FilePath device_dir(device_dir_str);
1131 // When VABC is enabled, we can't get device path for dynamic partitions in
1132 // target slot.
1133 const auto& partition_name_suffix =
1134 partition_name + SlotSuffixForSlotNumber(slot);
1135 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1136 IsDynamicPartition(partition_name, slot)) {
1137 return {
1138 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1139 .Append(partition_name_suffix)
1140 .value(),
1141 .is_dynamic = true}};
1142 }
1143
1144 // When looking up target partition devices, treat them as static if the
1145 // current payload doesn't encode them as dynamic partitions. This may happen
1146 // when applying a retrofit update on top of a dynamic-partitions-enabled
1147 // build.
1148 std::string device;
1149 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1150 (slot == current_slot || is_target_dynamic_)) {
1151 switch (GetDynamicPartitionDevice(device_dir,
1152 partition_name_suffix,
1153 slot,
1154 current_slot,
1155 not_in_payload,
1156 &device)) {
1157 case DynamicPartitionDeviceStatus::SUCCESS:
1158 return {{.rw_device_path = device,
1159 .readonly_device_path = device,
1160 .is_dynamic = true}};
1161
1162 case DynamicPartitionDeviceStatus::TRY_STATIC:
1163 break;
1164 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1165 default:
1166 return {};
1167 }
1168 }
1169 // Try static partitions.
1170 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1171 if (!DeviceExists(static_path)) {
1172 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1173 return {};
1174 }
1175
1176 return {{.rw_device_path = static_path,
1177 .readonly_device_path = static_path,
1178 .is_dynamic = false}};
1179 }
1180
IsSuperBlockDevice(const base::FilePath & device_dir,uint32_t current_slot,const std::string & partition_name_suffix)1181 bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1182 const base::FilePath& device_dir,
1183 uint32_t current_slot,
1184 const std::string& partition_name_suffix) {
1185 std::string source_device =
1186 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1187 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1188 return source_metadata->HasBlockDevice(partition_name_suffix);
1189 }
1190
1191 DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
GetDynamicPartitionDevice(const base::FilePath & device_dir,const std::string & partition_name_suffix,uint32_t slot,uint32_t current_slot,bool not_in_payload,std::string * device)1192 DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1193 const base::FilePath& device_dir,
1194 const std::string& partition_name_suffix,
1195 uint32_t slot,
1196 uint32_t current_slot,
1197 bool not_in_payload,
1198 std::string* device) {
1199 std::string super_device =
1200 device_dir.Append(GetSuperPartitionName(slot)).value();
1201
1202 auto builder = LoadMetadataBuilder(super_device, slot);
1203 if (builder == nullptr) {
1204 LOG(ERROR) << "No metadata in slot "
1205 << BootControlInterface::SlotName(slot);
1206 return DynamicPartitionDeviceStatus::ERROR;
1207 }
1208 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1209 LOG(INFO) << partition_name_suffix
1210 << " is not in super partition metadata.";
1211
1212 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1213 LOG(ERROR) << "The static partition " << partition_name_suffix
1214 << " is a block device for current metadata."
1215 << "It cannot be used as a logical partition.";
1216 return DynamicPartitionDeviceStatus::ERROR;
1217 }
1218
1219 return DynamicPartitionDeviceStatus::TRY_STATIC;
1220 }
1221
1222 if (slot == current_slot) {
1223 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1224 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1225 << "not mapped. Now try to map it.";
1226 } else {
1227 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1228 LOG(INFO) << partition_name_suffix
1229 << " is mapped on device mapper: " << *device;
1230 return DynamicPartitionDeviceStatus::SUCCESS;
1231 }
1232 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1233 return DynamicPartitionDeviceStatus::ERROR;
1234 }
1235 }
1236
1237 bool force_writable = (slot != current_slot) && !not_in_payload;
1238 if (MapPartitionOnDeviceMapper(
1239 super_device, partition_name_suffix, slot, force_writable, device)) {
1240 return DynamicPartitionDeviceStatus::SUCCESS;
1241 }
1242 return DynamicPartitionDeviceStatus::ERROR;
1243 }
1244
set_fake_mapped_devices(const std::set<std::string> & fake)1245 void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1246 const std::set<std::string>& fake) {
1247 mapped_devices_ = fake;
1248 }
1249
IsRecovery()1250 bool DynamicPartitionControlAndroid::IsRecovery() {
1251 return constants::kIsRecovery;
1252 }
1253
IsIncrementalUpdate(const DeltaArchiveManifest & manifest)1254 static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1255 const auto& partitions = manifest.partitions();
1256 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1257 return p.has_old_partition_info();
1258 });
1259 }
1260
DeleteSourcePartitions(MetadataBuilder * builder,uint32_t source_slot,const DeltaArchiveManifest & manifest)1261 bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1262 MetadataBuilder* builder,
1263 uint32_t source_slot,
1264 const DeltaArchiveManifest& manifest) {
1265 TEST_AND_RETURN_FALSE(IsRecovery());
1266
1267 if (IsIncrementalUpdate(manifest)) {
1268 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1269 << "be created.";
1270 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1271 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1272 << " Virtual A/B is not supported.";
1273 }
1274 return false;
1275 }
1276
1277 LOG(INFO) << "Will overwrite existing partitions. Slot "
1278 << BootControlInterface::SlotName(source_slot)
1279 << " may be unbootable until update finishes!";
1280 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1281 DeleteGroupsWithSuffix(builder, source_suffix);
1282
1283 return true;
1284 }
1285
1286 std::unique_ptr<AbstractAction>
GetCleanupPreviousUpdateAction(BootControlInterface * boot_control,PrefsInterface * prefs,CleanupPreviousUpdateActionDelegateInterface * delegate)1287 DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1288 BootControlInterface* boot_control,
1289 PrefsInterface* prefs,
1290 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1291 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1292 return std::make_unique<NoOpAction>();
1293 }
1294 return std::make_unique<CleanupPreviousUpdateAction>(
1295 prefs, boot_control, snapshot_.get(), delegate);
1296 }
1297
ResetUpdate(PrefsInterface * prefs)1298 bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1299 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1300 return true;
1301 }
1302 for (auto& list : dynamic_partition_list_) {
1303 list.clear();
1304 }
1305
1306 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1307 TEST_AND_RETURN_FALSE(prefs != nullptr);
1308
1309 // If the device has already booted into the target slot,
1310 // ResetUpdateProgress may pass but CancelUpdate fails.
1311 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1312 // space when it is done.
1313 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1314 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1315
1316 if (ExpectMetadataMounted()) {
1317 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1318 } else {
1319 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1320 << "not mounted";
1321 }
1322
1323 return true;
1324 }
1325
ListDynamicPartitionsForSlot(uint32_t slot,uint32_t current_slot,std::vector<std::string> * partitions)1326 bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1327 uint32_t slot,
1328 uint32_t current_slot,
1329 std::vector<std::string>* partitions) {
1330 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1331 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1332 << " slot: " << slot
1333 << " attempting to query dynamic partition metadata for target slot "
1334 "before PreparePartitionForUpdate() is called. The "
1335 "metadata in target slot isn't valid until "
1336 "PreparePartitionForUpdate() is called, contining execution would "
1337 "likely cause problems.";
1338 bool slot_enables_dynamic_partitions =
1339 GetDynamicPartitionsFeatureFlag().IsEnabled();
1340 // Check if the target slot has dynamic partitions, this may happen when
1341 // applying a retrofit package.
1342 if (slot != current_slot) {
1343 slot_enables_dynamic_partitions =
1344 slot_enables_dynamic_partitions && is_target_dynamic_;
1345 }
1346
1347 if (!slot_enables_dynamic_partitions) {
1348 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1349 return true;
1350 }
1351
1352 std::string device_dir_str;
1353 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1354 base::FilePath device_dir(device_dir_str);
1355 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1356 auto builder = LoadMetadataBuilder(super_device, slot);
1357 TEST_AND_RETURN_FALSE(builder != nullptr);
1358
1359 std::vector<std::string> result;
1360 auto suffix = SlotSuffixForSlotNumber(slot);
1361 for (const auto& group : builder->ListGroups()) {
1362 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1363 std::string_view partition_name = partition->name();
1364 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1365 continue;
1366 }
1367 result.emplace_back(partition_name);
1368 }
1369 }
1370 *partitions = std::move(result);
1371 return true;
1372 }
1373
VerifyExtentsForUntouchedPartitions(uint32_t source_slot,uint32_t target_slot,const std::vector<std::string> & partitions)1374 bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1375 uint32_t source_slot,
1376 uint32_t target_slot,
1377 const std::vector<std::string>& partitions) {
1378 std::string device_dir_str;
1379 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1380 base::FilePath device_dir(device_dir_str);
1381
1382 auto source_super_device =
1383 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1384 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1385 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1386
1387 auto target_super_device =
1388 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1389 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1390 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1391
1392 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1393 *source_builder, source_slot, *target_builder, target_slot, partitions);
1394 }
1395
ExpectMetadataMounted()1396 bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1397 // No need to mount metadata for non-Virtual A/B devices.
1398 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1399 return false;
1400 }
1401 // Intentionally not checking |metadata_device_| in Android mode.
1402 // /metadata should always be mounted in Android mode. If it isn't, let caller
1403 // fails when calling into SnapshotManager.
1404 if (!IsRecovery()) {
1405 return true;
1406 }
1407 // In recovery mode, explicitly check |metadata_device_|.
1408 return metadata_device_ != nullptr;
1409 }
1410
EnsureMetadataMounted()1411 bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1412 // No need to mount metadata for non-Virtual A/B devices.
1413 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1414 return true;
1415 }
1416
1417 if (metadata_device_ == nullptr) {
1418 metadata_device_ = snapshot_->EnsureMetadataMounted();
1419 }
1420 return metadata_device_ != nullptr;
1421 }
1422
1423 std::unique_ptr<android::snapshot::ISnapshotWriter>
OpenCowWriter(const std::string & partition_name,const std::optional<std::string> & source_path,bool is_append)1424 DynamicPartitionControlAndroid::OpenCowWriter(
1425 const std::string& partition_name,
1426 const std::optional<std::string>& source_path,
1427 bool is_append) {
1428 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1429
1430 auto super_device = GetSuperDevice();
1431 if (!super_device.has_value()) {
1432 return nullptr;
1433 }
1434 CreateLogicalPartitionParams params = {
1435 .block_device = super_device->value(),
1436 .metadata_slot = target_slot_,
1437 .partition_name = partition_name + suffix,
1438 .force_writable = true,
1439 .timeout_ms = kMapSnapshotTimeout};
1440 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1441 // it.
1442 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
1443 } // namespace chromeos_update_engine
1444
OpenCowFd(const std::string & unsuffixed_partition_name,const std::optional<std::string> & source_path,bool is_append)1445 std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
1446 const std::string& unsuffixed_partition_name,
1447 const std::optional<std::string>& source_path,
1448 bool is_append) {
1449 auto cow_writer =
1450 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1451 if (cow_writer == nullptr) {
1452 return nullptr;
1453 }
1454 if (!cow_writer->InitializeAppend(kEndOfInstallLabel)) {
1455 LOG(ERROR) << "Failed to InitializeAppend(" << kEndOfInstallLabel << ")";
1456 return nullptr;
1457 }
1458 auto reader = cow_writer->OpenReader();
1459 if (reader == nullptr) {
1460 LOG(ERROR) << "ICowWriter::OpenReader() failed.";
1461 return nullptr;
1462 }
1463 return std::make_unique<CowWriterFileDescriptor>(std::move(cow_writer),
1464 std::move(reader));
1465 }
1466
GetSuperDevice()1467 std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1468 std::string device_dir_str;
1469 if (!GetDeviceDir(&device_dir_str)) {
1470 LOG(ERROR) << "Failed to get device dir!";
1471 return {};
1472 }
1473 base::FilePath device_dir(device_dir_str);
1474 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1475 return super_device;
1476 }
1477
MapAllPartitions()1478 bool DynamicPartitionControlAndroid::MapAllPartitions() {
1479 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
1480 }
1481
IsDynamicPartition(const std::string & partition_name,uint32_t slot)1482 bool DynamicPartitionControlAndroid::IsDynamicPartition(
1483 const std::string& partition_name, uint32_t slot) {
1484 if (slot >= dynamic_partition_list_.size()) {
1485 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1486 << dynamic_partition_list_.size() << " slots";
1487 return false;
1488 }
1489 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1490 if (dynamic_partition_list.empty() &&
1491 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1492 // Use the DAP config of the target slot.
1493 CHECK(ListDynamicPartitionsForSlot(
1494 slot, source_slot_, &dynamic_partition_list));
1495 }
1496 return std::find(dynamic_partition_list.begin(),
1497 dynamic_partition_list.end(),
1498 partition_name) != dynamic_partition_list.end();
1499 }
1500
UpdateUsesSnapshotCompression()1501 bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
1502 return GetVirtualAbFeatureFlag().IsEnabled() &&
1503 snapshot_->UpdateUsesCompression();
1504 }
1505
1506 } // namespace chromeos_update_engine
1507