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