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