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