blob: 157579698da1058c2f1e1d69b2daabed7afeb7d4 [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070035#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070036#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070037#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080038#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070039#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080040#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040041#include <liblp/liblp.h>
42#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070043#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070044#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070045
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/aosp/cleanup_previous_update_action.h"
47#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070048#include "update_engine/common/boot_control_interface.h"
49#include "update_engine/common/utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070050#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070051
52using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070053using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070054using android::base::Join;
55using android::dm::DeviceMapper;
56using android::dm::DmDeviceState;
57using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070058using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070059using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070060using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070061using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070062using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080063using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070064using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070065using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080066using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080067using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070068using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080069using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070070
71namespace chromeos_update_engine {
72
Yifan Hong6e706b12018-11-09 16:50:51 -080073constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
74constexpr char kRetrfoitDynamicPartitions[] =
75 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070076constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
77constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040078constexpr char kVirtualAbCompressionEnabled[] =
79 "ro.virtual_ab.compression.enabled";
80
81// Currently, android doesn't have a retrofit prop for VAB Compression. However,
82// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
83// is here just to simplify code. Replace it with real retrofit prop name once
84// there is one.
85constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070086constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070087// Map timeout for dynamic partitions.
88constexpr std::chrono::milliseconds kMapTimeout{1000};
89// Map timeout for dynamic partitions with snapshots. Since several devices
90// needs to be mapped, this timeout is longer than |kMapTimeout|.
91constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
92
Yifan Hong537802d2018-08-15 13:15:42 -070093DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070094 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070095}
96
Yifan Hong186bb682019-07-23 14:04:39 -070097static FeatureFlag GetFeatureFlag(const char* enable_prop,
98 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -040099 // Default retrofit to false if retrofit_prop is empty.
100 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
101 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700102 bool enabled = GetBoolProperty(enable_prop, false);
103 if (retrofit && !enabled) {
104 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
105 << " is not. These sysprops are inconsistent. Assume that "
106 << enable_prop << " is true from now on.";
107 }
108 if (retrofit) {
109 return FeatureFlag(FeatureFlag::Value::RETROFIT);
110 }
111 if (enabled) {
112 return FeatureFlag(FeatureFlag::Value::LAUNCH);
113 }
114 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700115}
116
Yifan Hongb38e1af2019-10-17 14:59:22 -0700117DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
118 : dynamic_partitions_(
119 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400120 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
121 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
122 kVirtualAbCompressionRetrofit)) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700123 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800124 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700125 } else {
126 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700127 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700128 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700129}
130
Yifan Hong186bb682019-07-23 14:04:39 -0700131FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700132 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800133}
134
Yifan Hong413d5722019-07-23 14:21:09 -0700135FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700136 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700137}
138
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400139FeatureFlag
140DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
141 return virtual_ab_compression_;
142}
143
Yifan Hongf5261562020-03-10 10:28:10 -0700144bool DynamicPartitionControlAndroid::OptimizeOperation(
145 const std::string& partition_name,
146 const InstallOperation& operation,
147 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000148 switch (operation.type()) {
149 case InstallOperation::SOURCE_COPY:
150 return target_supports_snapshot_ &&
151 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800152 mapped_devices_.count(partition_name +
153 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700154 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000155 break;
156 default:
157 break;
158 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000159 return false;
160}
161
Yifan Hong8546a712019-03-28 14:42:53 -0700162bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700163 const std::string& super_device,
164 const std::string& target_partition_name,
165 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700166 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700167 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700168 CreateLogicalPartitionParams params = {
169 .block_device = super_device,
170 .metadata_slot = slot,
171 .partition_name = target_partition_name,
172 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700173 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700174 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700175 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700176 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700177 // Only target partitions are mapped with force_writable. On Virtual
178 // A/B devices, target partitions may overlap with source partitions, so
179 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700180 // One exception is when /metadata is not mounted. Fallback to
181 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700182 params.timeout_ms = kMapSnapshotTimeout;
183 success = snapshot_->MapUpdateSnapshot(params, path);
184 } else {
185 params.timeout_ms = kMapTimeout;
186 success = CreateLogicalPartition(params, path);
187 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700188
Yifan Hong420db9b2019-07-23 20:50:33 -0700189 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700190 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
191 << super_device << " on device mapper.";
192 return false;
193 }
194 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700195 << " to device mapper (force_writable = " << force_writable
196 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700197 mapped_devices_.insert(target_partition_name);
198 return true;
199}
200
Yifan Hong8546a712019-03-28 14:42:53 -0700201bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
202 const std::string& super_device,
203 const std::string& target_partition_name,
204 uint32_t slot,
205 bool force_writable,
206 std::string* path) {
207 DmDeviceState state = GetState(target_partition_name);
208 if (state == DmDeviceState::ACTIVE) {
209 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
210 if (GetDmDevicePathByName(target_partition_name, path)) {
211 LOG(INFO) << target_partition_name
212 << " is mapped on device mapper: " << *path;
213 return true;
214 }
215 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
216 return false;
217 }
218 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
219 // the device might be mapped incorrectly before. Attempt to unmap it.
220 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
221 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
222 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700223 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700224 LOG(ERROR) << target_partition_name
225 << " is mapped before the update, and it cannot be unmapped.";
226 return false;
227 }
228 state = GetState(target_partition_name);
229 if (state != DmDeviceState::INVALID) {
230 LOG(ERROR) << target_partition_name << " is unmapped but state is "
231 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
232 return false;
233 }
234 }
235 if (state == DmDeviceState::INVALID) {
236 return MapPartitionInternal(
237 super_device, target_partition_name, slot, force_writable, path);
238 }
239
240 LOG(ERROR) << target_partition_name
241 << " is mapped on device mapper but state is unknown: "
242 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
243 return false;
244}
245
Yifan Hong537802d2018-08-15 13:15:42 -0700246bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700247 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700248 if (DeviceMapper::Instance().GetState(target_partition_name) !=
249 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700250 // Partitions at target slot on non-Virtual A/B devices are mapped as
251 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
252 // preopt apps as dm-linear.
253 // Call DestroyLogicalPartition to handle these cases.
254 bool success = DestroyLogicalPartition(target_partition_name);
255
256 // On a Virtual A/B device, |target_partition_name| may be a leftover from
257 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700258 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700259 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700260 } else {
261 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
262 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700263 }
264
265 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700266 LOG(ERROR) << "Cannot unmap " << target_partition_name
267 << " from device mapper.";
268 return false;
269 }
270 LOG(INFO) << "Successfully unmapped " << target_partition_name
271 << " from device mapper.";
272 }
273 mapped_devices_.erase(target_partition_name);
274 return true;
275}
276
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400277bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700278 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400279 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700280 }
Yifan Hong537802d2018-08-15 13:15:42 -0700281 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
282 // a copy is needed for the loop.
283 std::set<std::string> mapped = mapped_devices_;
284 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
285 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700286 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700287 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400288 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700289}
290
291void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700292 UnmapAllPartitions();
293 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700294}
295
296bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
297 return base::PathExists(base::FilePath(path));
298}
299
300android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
301 const std::string& name) {
302 return DeviceMapper::Instance().GetState(name);
303}
304
305bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
306 const std::string& name, std::string* path) {
307 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
308}
309
310std::unique_ptr<MetadataBuilder>
311DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700312 const std::string& super_device, uint32_t slot) {
313 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
314 if (builder == nullptr) {
315 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
316 << " in " << super_device;
317 return nullptr;
318 }
319 LOG(INFO) << "Loaded metadata from slot "
320 << BootControlInterface::SlotName(slot) << " in " << super_device;
321 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700322}
323
324std::unique_ptr<MetadataBuilder>
325DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800326 const std::string& super_device,
327 uint32_t source_slot,
328 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700329 bool always_keep_source_slot = !target_supports_snapshot_;
330 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
331 super_device,
332 source_slot,
333 target_slot,
334 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700335 if (builder == nullptr) {
336 LOG(WARNING) << "No metadata slot "
337 << BootControlInterface::SlotName(source_slot) << " in "
338 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700339 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700340 }
Tianjie24f96092020-06-30 12:26:25 -0700341 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700342 << BootControlInterface::SlotName(source_slot) << " in "
343 << super_device;
344 return builder;
345}
346
347bool DynamicPartitionControlAndroid::StoreMetadata(
348 const std::string& super_device,
349 MetadataBuilder* builder,
350 uint32_t target_slot) {
351 auto metadata = builder->Export();
352 if (metadata == nullptr) {
353 LOG(ERROR) << "Cannot export metadata to slot "
354 << BootControlInterface::SlotName(target_slot) << " in "
355 << super_device;
356 return false;
357 }
358
Yifan Hong186bb682019-07-23 14:04:39 -0700359 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800360 if (!FlashPartitionTable(super_device, *metadata)) {
361 LOG(ERROR) << "Cannot write metadata to " << super_device;
362 return false;
363 }
364 LOG(INFO) << "Written metadata to " << super_device;
365 } else {
366 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
367 LOG(ERROR) << "Cannot write metadata to slot "
368 << BootControlInterface::SlotName(target_slot) << " in "
369 << super_device;
370 return false;
371 }
372 LOG(INFO) << "Copied metadata to slot "
373 << BootControlInterface::SlotName(target_slot) << " in "
374 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700375 }
376
Yifan Hong537802d2018-08-15 13:15:42 -0700377 return true;
378}
379
380bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
381 // We can't use fs_mgr to look up |partition_name| because fstab
382 // doesn't list every slot partition (it uses the slotselect option
383 // to mask the suffix).
384 //
385 // We can however assume that there's an entry for the /misc mount
386 // point and use that to get the device file for the misc
387 // partition. This helps us locate the disk that |partition_name|
388 // resides on. From there we'll assume that a by-name scheme is used
389 // so we can just replace the trailing "misc" by the given
390 // |partition_name| and suffix corresponding to |slot|, e.g.
391 //
392 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
393 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
394 //
395 // If needed, it's possible to relax the by-name assumption in the
396 // future by trawling /sys/block looking for the appropriate sibling
397 // of misc and then finding an entry in /dev matching the sysfs
398 // entry.
399
400 std::string err, misc_device = get_bootloader_message_blk_device(&err);
401 if (misc_device.empty()) {
402 LOG(ERROR) << "Unable to get misc block device: " << err;
403 return false;
404 }
405
406 if (!utils::IsSymlink(misc_device.c_str())) {
407 LOG(ERROR) << "Device file " << misc_device << " for /misc "
408 << "is not a symlink.";
409 return false;
410 }
411 *out = base::FilePath(misc_device).DirName().value();
412 return true;
413}
Yifan Hong012508e2019-07-22 18:30:40 -0700414
415bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
416 uint32_t source_slot,
417 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700418 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800419 bool update,
420 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800421 source_slot_ = source_slot;
422 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800423 if (required_size != nullptr) {
424 *required_size = 0;
425 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800426
Yifan Hong3a1a5612019-11-05 16:34:32 -0800427 if (fs_mgr_overlayfs_is_setup()) {
428 // Non DAP devices can use overlayfs as well.
429 LOG(WARNING)
430 << "overlayfs overrides are active and can interfere with our "
431 "resources.\n"
432 << "run adb enable-verity to deactivate if required and try again.";
433 }
434
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700435 // If metadata is erased but not formatted, it is possible to not mount
436 // it in recovery. It is acceptable to skip mounting and choose fallback path
437 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
438 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700439
440 if (update) {
441 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
442 }
443
Yifan Hong3a1a5612019-11-05 16:34:32 -0800444 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
445 return true;
446 }
447
448 if (target_slot == source_slot) {
449 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
450 return false;
451 }
452
Yifan Hongf6f75c22020-07-31 15:20:25 -0700453 if (!SetTargetBuildVars(manifest)) {
454 return false;
455 }
456
Yifan Hong3a1a5612019-11-05 16:34:32 -0800457 // Although the current build supports dynamic partitions, the given payload
458 // doesn't use it for target partitions. This could happen when applying a
459 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800460 if (!is_target_dynamic_) {
461 return true;
462 }
463
Yifan Hongf0f4a912019-09-26 17:51:33 -0700464 if (!update)
465 return true;
466
Yifan Hongbae27842019-10-24 16:56:12 -0700467 bool delete_source = false;
468
Yifan Hong6d888562019-10-01 13:00:31 -0700469 if (GetVirtualAbFeatureFlag().IsEnabled()) {
470 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
471 // called before calling UnmapUpdateSnapshot.
472 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
473 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700474 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
475 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700476 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700477 if (PrepareSnapshotPartitionsForUpdate(
478 source_slot, target_slot, manifest, required_size)) {
479 return true;
480 }
481
482 // Virtual A/B device doing Virtual A/B update in Android mode must use
483 // snapshots.
484 if (!IsRecovery()) {
485 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
486 << "mode";
487 return false;
488 }
489
490 delete_source = true;
491 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
492 << "Attempt to overwrite existing partitions if possible";
493 } else {
494 // Downgrading to an non-Virtual A/B build or is secondary OTA.
495 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
496 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700497 }
Yifan Hongbae27842019-10-24 16:56:12 -0700498
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700499 // In recovery, if /metadata is not mounted, it is likely that metadata
500 // partition is erased and not formatted yet. After sideloading, when
501 // rebooting into the new version, init will erase metadata partition,
502 // hence the failure of CancelUpdate() can be ignored here.
503 // However, if metadata is mounted and CancelUpdate fails, sideloading
504 // should not proceed because during next boot, snapshots will overlay on
505 // the devices incorrectly.
506 if (ExpectMetadataMounted()) {
507 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
508 } else {
509 LOG(INFO) << "Skip canceling previous update because metadata is not "
510 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700511 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700512 }
Yifan Hongbae27842019-10-24 16:56:12 -0700513
Tianjie24f96092020-06-30 12:26:25 -0700514 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700515 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
516 source_slot, target_slot, manifest, delete_source));
517
518 if (required_size != nullptr) {
519 *required_size = 0;
520 }
521 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700522}
523
Yifan Hongf6f75c22020-07-31 15:20:25 -0700524bool DynamicPartitionControlAndroid::SetTargetBuildVars(
525 const DeltaArchiveManifest& manifest) {
526 // Precondition: current build supports dynamic partition.
527 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
528
529 bool is_target_dynamic =
530 !manifest.dynamic_partition_metadata().groups().empty();
531 bool target_supports_snapshot =
532 manifest.dynamic_partition_metadata().snapshot_enabled();
533
534 if (manifest.partial_update()) {
535 // Partial updates requires DAP. On partial updates that does not involve
536 // dynamic partitions, groups() can be empty, so also assume
537 // is_target_dynamic in this case. This assumption should be safe because we
538 // also check target_supports_snapshot below, which presumably also implies
539 // target build supports dynamic partition.
540 if (!is_target_dynamic) {
541 LOG(INFO) << "Assuming target build supports dynamic partitions for "
542 "partial updates.";
543 is_target_dynamic = true;
544 }
545
546 // Partial updates requires Virtual A/B. Double check that both current
547 // build and target build supports Virtual A/B.
548 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
549 LOG(ERROR) << "Partial update cannot be applied on a device that does "
550 "not support snapshots.";
551 return false;
552 }
553 if (!target_supports_snapshot) {
554 LOG(ERROR) << "Cannot apply partial update to a build that does not "
555 "support snapshots.";
556 return false;
557 }
558 }
559
560 // Store the flags.
561 is_target_dynamic_ = is_target_dynamic;
562 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
563 // snapshots would not work without dynamic partition.
564 if (is_target_dynamic_) {
565 target_supports_snapshot_ = target_supports_snapshot;
566 }
567 return true;
568}
569
Yifan Hong29692902020-03-26 12:47:05 -0700570namespace {
571// Try our best to erase AVB footer.
572class AvbFooterEraser {
573 public:
574 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
575 bool Erase() {
576 // Try to mark the block device read-only. Ignore any
577 // failure since this won't work when passing regular files.
578 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
579
580 fd_.reset(new EintrSafeFileDescriptor());
581 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
582 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
583
584 // Need to write end-AVB_FOOTER_SIZE to end.
585 static_assert(AVB_FOOTER_SIZE > 0);
586 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
587 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
588 uint64_t write_size = AVB_FOOTER_SIZE;
589 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
590 << (offset + write_size) << "] (" << write_size << " bytes)";
591 brillo::Blob zeros(write_size);
592 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
593 return true;
594 }
595 ~AvbFooterEraser() {
596 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
597 if (!fd_->Close()) {
598 LOG(WARNING) << "Failed to close fd for " << path_;
599 }
600 }
601
602 private:
603 std::string path_;
604 FileDescriptorPtr fd_;
605};
606
607} // namespace
608
609std::optional<bool>
610DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
611 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
612 if (prefix.empty()) {
613 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
614 return std::nullopt;
615 }
616 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
617 return IsAvbEnabledInFstab(path);
618}
619
620std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
621 const std::string& path) {
622 Fstab fstab;
623 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700624 PLOG(WARNING) << "Cannot read fstab from " << path;
625 if (errno == ENOENT) {
626 return false;
627 }
Yifan Hong29692902020-03-26 12:47:05 -0700628 return std::nullopt;
629 }
630 for (const auto& entry : fstab) {
631 if (!entry.avb_keys.empty()) {
632 return true;
633 }
634 }
635 return false;
636}
637
638bool DynamicPartitionControlAndroid::GetSystemOtherPath(
639 uint32_t source_slot,
640 uint32_t target_slot,
641 const std::string& partition_name_suffix,
642 std::string* path,
643 bool* should_unmap) {
644 path->clear();
645 *should_unmap = false;
646
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530647 // Check that AVB is enabled on system_other before erasing.
648 auto has_avb = IsAvbEnabledOnSystemOther();
649 TEST_AND_RETURN_FALSE(has_avb.has_value());
650 if (!has_avb.value()) {
651 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
652 return true;
653 }
Yifan Hong29692902020-03-26 12:47:05 -0700654
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530655 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700656 // Found unexpected avb_keys for system_other on devices retrofitting
657 // dynamic partitions. Previous crash in update_engine may leave logical
658 // partitions mapped on physical system_other partition. It is difficult to
659 // handle these cases. Just fail.
660 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
661 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
662 << "retrofit dynamic partitions. They should not have AVB "
663 << "enabled on system_other.";
664 return false;
665 }
666 }
667
668 std::string device_dir_str;
669 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
670 base::FilePath device_dir(device_dir_str);
671
672 // On devices without dynamic partition, search for static partitions.
673 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
674 *path = device_dir.Append(partition_name_suffix).value();
675 TEST_AND_RETURN_FALSE(DeviceExists(*path));
676 return true;
677 }
678
679 auto source_super_device =
680 device_dir.Append(GetSuperPartitionName(source_slot)).value();
681
682 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
683 if (builder == nullptr) {
684 if (IsRecovery()) {
685 // It might be corrupted for some reason. It should still be able to
686 // sideload.
687 LOG(WARNING) << "Super partition metadata cannot be read from the source "
688 << "slot, skip erasing.";
689 return true;
690 } else {
691 // Device has booted into Android mode, indicating that the super
692 // partition metadata should be there.
693 LOG(ERROR) << "Super partition metadata cannot be read from the source "
694 << "slot. This is unexpected on devices with dynamic "
695 << "partitions enabled.";
696 return false;
697 }
698 }
699 auto p = builder->FindPartition(partition_name_suffix);
700 if (p == nullptr) {
701 // If the source slot is flashed without system_other, it does not exist
702 // in super partition metadata at source slot. It is safe to skip it.
703 LOG(INFO) << "Can't find " << partition_name_suffix
704 << " in metadata source slot, skip erasing.";
705 return true;
706 }
707 // System_other created by flashing tools should be erased.
708 // If partition is created by update_engine (via NewForUpdate), it is a
709 // left-over partition from the previous update and does not contain
710 // system_other, hence there is no need to erase.
711 // Note the reverse is not necessary true. If the flag is not set, we don't
712 // know if the partition is created by update_engine or by flashing tools
713 // because older versions of super partition metadata does not contain this
714 // flag. It is okay to erase the AVB footer anyways.
715 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
716 LOG(INFO) << partition_name_suffix
717 << " does not contain system_other, skip erasing.";
718 return true;
719 }
720
Yifan Hong64331b32020-05-13 16:50:40 -0700721 if (p->size() < AVB_FOOTER_SIZE) {
722 LOG(INFO) << partition_name_suffix << " has length " << p->size()
723 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
724 << "), skip erasing.";
725 return true;
726 }
727
Yifan Hong29692902020-03-26 12:47:05 -0700728 // Delete any pre-existing device with name |partition_name_suffix| and
729 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700730 // In recovery, metadata might not be mounted, and
731 // UnmapPartitionOnDeviceMapper might fail. However,
732 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700733 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
734 // Use CreateLogicalPartition directly to avoid mapping with existing
735 // snapshots.
736 CreateLogicalPartitionParams params = {
737 .block_device = source_super_device,
738 .metadata_slot = source_slot,
739 .partition_name = partition_name_suffix,
740 .force_writable = true,
741 .timeout_ms = kMapTimeout,
742 };
743 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
744 *should_unmap = true;
745 return true;
746}
747
748bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
749 uint32_t source_slot, uint32_t target_slot) {
750 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
751
752 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
753 const std::string partition_name_suffix = "system" + target_suffix;
754
755 std::string path;
756 bool should_unmap = false;
757
758 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
759 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
760
761 if (path.empty()) {
762 return true;
763 }
764
765 bool ret = AvbFooterEraser(path).Erase();
766
767 // Delete |partition_name_suffix| from device mapper and from
768 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700769 // In recovery, metadata might not be mounted, and
770 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
771 // should be called. If DestroyLogicalPartition does fail, it is still okay
772 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700773 if (should_unmap) {
774 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
775 }
776
777 return ret;
778}
779
Yifan Hong420db9b2019-07-23 20:50:33 -0700780bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
781 uint32_t source_slot,
782 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700783 const DeltaArchiveManifest& manifest,
784 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700785 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
786
787 // Unmap all the target dynamic partitions because they would become
788 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700789 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
790 for (const auto& partition_name : group.partition_names()) {
791 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700792 return false;
793 }
794 }
795 }
796
797 std::string device_dir_str;
798 if (!GetDeviceDir(&device_dir_str)) {
799 return false;
800 }
801 base::FilePath device_dir(device_dir_str);
802 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700803 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700804
805 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
806 if (builder == nullptr) {
807 LOG(ERROR) << "No metadata at "
808 << BootControlInterface::SlotName(source_slot);
809 return false;
810 }
811
Yifan Hongbae27842019-10-24 16:56:12 -0700812 if (delete_source) {
813 TEST_AND_RETURN_FALSE(
814 DeleteSourcePartitions(builder.get(), source_slot, manifest));
815 }
816
Yifan Hong13d41cb2019-09-16 13:18:22 -0700817 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700818 return false;
819 }
820
821 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700822 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700823 return StoreMetadata(target_device, builder.get(), target_slot);
824}
825
Yifan Hong420db9b2019-07-23 20:50:33 -0700826bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
827 uint32_t source_slot,
828 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800829 const DeltaArchiveManifest& manifest,
830 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700831 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700832 if (!snapshot_->BeginUpdate()) {
833 LOG(ERROR) << "Cannot begin new update.";
834 return false;
835 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800836 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
837 if (!ret) {
838 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
839 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800840 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800841 *required_size = ret.required_size();
842 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700843 return false;
844 }
845 return true;
846}
847
Yifan Hong700d7c12019-07-23 20:49:16 -0700848std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
849 uint32_t slot) {
850 return fs_mgr_get_super_partition_name(slot);
851}
852
Yifan Hong012508e2019-07-22 18:30:40 -0700853bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
854 MetadataBuilder* builder,
855 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700856 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700857 // Check preconditions.
858 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
859 << "UpdatePartitionMetadata is called on a Virtual A/B device "
860 "but source partitions is not deleted. This is not allowed.";
861
Yifan Honga4e7da32019-09-30 18:25:03 -0700862 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
863 // COW group needs to be deleted to ensure there are enough space to create
864 // target partitions.
865 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
866
Yifan Hong012508e2019-07-22 18:30:40 -0700867 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
868 DeleteGroupsWithSuffix(builder, target_suffix);
869
870 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700871 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
872 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700873 }
874
875 std::string expr;
876 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700877 // On device retrofitting dynamic partitions, allocatable_space = super.
878 // On device launching dynamic partitions w/o VAB,
879 // allocatable_space = super / 2.
880 // On device launching dynamic partitions with VAB, allocatable_space = super.
881 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
882 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700883 allocatable_space /= 2;
884 expr = "half of ";
885 }
886 if (total_size > allocatable_space) {
887 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
888 << " (" << total_size << ") has exceeded " << expr
889 << "allocatable space for dynamic partitions "
890 << allocatable_space << ".";
891 return false;
892 }
893
Yifan Hong13d41cb2019-09-16 13:18:22 -0700894 // name of partition(e.g. "system") -> size in bytes
895 std::map<std::string, uint64_t> partition_sizes;
896 for (const auto& partition : manifest.partitions()) {
897 partition_sizes.emplace(partition.partition_name(),
898 partition.new_partition_info().size());
899 }
900
901 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
902 auto group_name_suffix = group.name() + target_suffix;
903 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700904 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700905 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700906 return false;
907 }
908 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700909 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700910
Yifan Hong13d41cb2019-09-16 13:18:22 -0700911 for (const auto& partition_name : group.partition_names()) {
912 auto partition_sizes_it = partition_sizes.find(partition_name);
913 if (partition_sizes_it == partition_sizes.end()) {
914 // TODO(tbao): Support auto-filling partition info for framework-only
915 // OTA.
916 LOG(ERROR) << "dynamic_partition_metadata contains partition "
917 << partition_name << " but it is not part of the manifest. "
918 << "This is not supported.";
919 return false;
920 }
921 uint64_t partition_size = partition_sizes_it->second;
922
923 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700924 Partition* p = builder->AddPartition(
925 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
926 if (!p) {
927 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
928 << " to group " << group_name_suffix;
929 return false;
930 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700931 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700932 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700933 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700934 return false;
935 }
936 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700937 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700938 }
939 }
940
941 return true;
942}
943
Yifan Hong7b3910a2020-03-24 17:47:32 -0700944bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700945 if (ExpectMetadataMounted()) {
946 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
947 LOG(INFO) << "Snapshot writes are done.";
948 return snapshot_->FinishedSnapshotWrites(powerwash_required);
949 }
950 } else {
951 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
952 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700953 }
954 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700955}
956
Yifan Hong3a1a5612019-11-05 16:34:32 -0800957bool DynamicPartitionControlAndroid::GetPartitionDevice(
958 const std::string& partition_name,
959 uint32_t slot,
960 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700961 bool not_in_payload,
962 std::string* device,
963 bool* is_dynamic) {
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500964 auto partition_dev = GetPartitionDevice(partition_name, slot, current_slot);
965 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800966 return false;
967 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500968 if (device) {
969 *device = std::move(partition_dev->rw_device_path);
970 }
971 if (is_dynamic) {
972 *is_dynamic = partition_dev->is_dynamic;
973 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800974 return true;
975}
976
Tianjie51a5a392020-06-03 14:39:32 -0700977bool DynamicPartitionControlAndroid::GetPartitionDevice(
978 const std::string& partition_name,
979 uint32_t slot,
980 uint32_t current_slot,
981 std::string* device) {
982 return GetPartitionDevice(
983 partition_name, slot, current_slot, false, device, nullptr);
984}
985
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500986static std::string GetStaticDevicePath(
987 const base::FilePath& device_dir,
988 const std::string& partition_name_suffixed) {
989 base::FilePath path = device_dir.Append(partition_name_suffixed);
990 return path.value();
991}
992
993std::optional<PartitionDevice>
994DynamicPartitionControlAndroid::GetPartitionDevice(
995 const std::string& partition_name,
996 uint32_t slot,
997 uint32_t current_slot,
998 bool not_in_payload) {
999 std::string device_dir_str;
1000 if (!GetDeviceDir(&device_dir_str)) {
1001 LOG(ERROR) << "Failed to GetDeviceDir()";
1002 return {};
1003 }
1004 const base::FilePath device_dir(device_dir_str);
1005 // When VABC is enabled, we can't get device path for dynamic partitions in
1006 // target slot.
1007 const auto& partition_name_suffix =
1008 partition_name + SlotSuffixForSlotNumber(slot);
1009 if (GetVirtualAbCompressionFeatureFlag().IsEnabled() &&
1010 IsDynamicPartition(partition_name) && slot != current_slot) {
1011 return {{.mountable_device_path =
1012 GetStaticDevicePath(device_dir, partition_name_suffix),
1013 .is_dynamic = true}};
1014 }
1015
1016 // When looking up target partition devices, treat them as static if the
1017 // current payload doesn't encode them as dynamic partitions. This may happen
1018 // when applying a retrofit update on top of a dynamic-partitions-enabled
1019 // build.
1020 std::string device;
1021 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1022 (slot == current_slot || is_target_dynamic_)) {
1023 switch (GetDynamicPartitionDevice(device_dir,
1024 partition_name_suffix,
1025 slot,
1026 current_slot,
1027 not_in_payload,
1028 &device)) {
1029 case DynamicPartitionDeviceStatus::SUCCESS:
1030 return {{.rw_device_path = device,
1031 .mountable_device_path = device,
1032 .is_dynamic = true}};
1033
1034 case DynamicPartitionDeviceStatus::TRY_STATIC:
1035 break;
1036 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1037 default:
1038 return {};
1039 }
1040 }
1041 // Try static partitions.
1042 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1043 if (!DeviceExists(static_path)) {
1044 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1045 return {};
1046 }
1047
1048 return {{.rw_device_path = static_path,
1049 .mountable_device_path = static_path,
1050 .is_dynamic = false}};
1051}
1052
Yifan Hong3a1a5612019-11-05 16:34:32 -08001053bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1054 const base::FilePath& device_dir,
1055 uint32_t current_slot,
1056 const std::string& partition_name_suffix) {
1057 std::string source_device =
1058 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1059 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1060 return source_metadata->HasBlockDevice(partition_name_suffix);
1061}
1062
1063DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1064DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1065 const base::FilePath& device_dir,
1066 const std::string& partition_name_suffix,
1067 uint32_t slot,
1068 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001069 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001070 std::string* device) {
1071 std::string super_device =
1072 device_dir.Append(GetSuperPartitionName(slot)).value();
1073
1074 auto builder = LoadMetadataBuilder(super_device, slot);
1075 if (builder == nullptr) {
1076 LOG(ERROR) << "No metadata in slot "
1077 << BootControlInterface::SlotName(slot);
1078 return DynamicPartitionDeviceStatus::ERROR;
1079 }
1080 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1081 LOG(INFO) << partition_name_suffix
1082 << " is not in super partition metadata.";
1083
1084 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1085 LOG(ERROR) << "The static partition " << partition_name_suffix
1086 << " is a block device for current metadata."
1087 << "It cannot be used as a logical partition.";
1088 return DynamicPartitionDeviceStatus::ERROR;
1089 }
1090
1091 return DynamicPartitionDeviceStatus::TRY_STATIC;
1092 }
1093
1094 if (slot == current_slot) {
1095 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1096 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1097 << "not mapped. Now try to map it.";
1098 } else {
1099 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1100 LOG(INFO) << partition_name_suffix
1101 << " is mapped on device mapper: " << *device;
1102 return DynamicPartitionDeviceStatus::SUCCESS;
1103 }
1104 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1105 return DynamicPartitionDeviceStatus::ERROR;
1106 }
1107 }
1108
Tianjie51a5a392020-06-03 14:39:32 -07001109 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001110 if (MapPartitionOnDeviceMapper(
1111 super_device, partition_name_suffix, slot, force_writable, device)) {
1112 return DynamicPartitionDeviceStatus::SUCCESS;
1113 }
1114 return DynamicPartitionDeviceStatus::ERROR;
1115}
1116
Yifan Hong6eec9952019-12-04 13:12:01 -08001117void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1118 const std::set<std::string>& fake) {
1119 mapped_devices_ = fake;
1120}
1121
Yifan Hongbae27842019-10-24 16:56:12 -07001122bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001123 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001124}
1125
1126static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1127 const auto& partitions = manifest.partitions();
1128 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1129 return p.has_old_partition_info();
1130 });
1131}
1132
1133bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1134 MetadataBuilder* builder,
1135 uint32_t source_slot,
1136 const DeltaArchiveManifest& manifest) {
1137 TEST_AND_RETURN_FALSE(IsRecovery());
1138
1139 if (IsIncrementalUpdate(manifest)) {
1140 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1141 << "be created.";
1142 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1143 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1144 << " Virtual A/B is not supported.";
1145 }
1146 return false;
1147 }
1148
1149 LOG(INFO) << "Will overwrite existing partitions. Slot "
1150 << BootControlInterface::SlotName(source_slot)
1151 << "may be unbootable until update finishes!";
1152 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1153 DeleteGroupsWithSuffix(builder, source_suffix);
1154
1155 return true;
1156}
1157
Yifan Hong90965502020-02-19 15:22:47 -08001158std::unique_ptr<AbstractAction>
1159DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1160 BootControlInterface* boot_control,
1161 PrefsInterface* prefs,
1162 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1163 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1164 return std::make_unique<NoOpAction>();
1165 }
1166 return std::make_unique<CleanupPreviousUpdateAction>(
1167 prefs, boot_control, snapshot_.get(), delegate);
1168}
1169
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001170bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1171 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1172 return true;
1173 }
1174
1175 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1176 TEST_AND_RETURN_FALSE(prefs != nullptr);
1177
1178 // If the device has already booted into the target slot,
1179 // ResetUpdateProgress may pass but CancelUpdate fails.
1180 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1181 // space when it is done.
1182 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1183 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1184
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001185 if (ExpectMetadataMounted()) {
1186 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1187 } else {
1188 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1189 << "not mounted";
1190 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001191
1192 return true;
1193}
1194
Tianjie99d570d2020-06-04 14:57:19 -07001195bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1196 uint32_t current_slot, std::vector<std::string>* partitions) {
1197 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1198 LOG(ERROR) << "Dynamic partition is not enabled";
1199 return false;
1200 }
1201
1202 std::string device_dir_str;
1203 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1204 base::FilePath device_dir(device_dir_str);
1205 auto super_device =
1206 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1207 auto builder = LoadMetadataBuilder(super_device, current_slot);
1208 TEST_AND_RETURN_FALSE(builder != nullptr);
1209
1210 std::vector<std::string> result;
1211 auto suffix = SlotSuffixForSlotNumber(current_slot);
1212 for (const auto& group : builder->ListGroups()) {
1213 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1214 std::string_view partition_name = partition->name();
1215 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1216 continue;
1217 }
1218 result.emplace_back(partition_name);
1219 }
1220 }
1221 *partitions = std::move(result);
1222 return true;
1223}
1224
Tianjie24f96092020-06-30 12:26:25 -07001225bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1226 uint32_t source_slot,
1227 uint32_t target_slot,
1228 const std::vector<std::string>& partitions) {
1229 std::string device_dir_str;
1230 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1231 base::FilePath device_dir(device_dir_str);
1232
1233 auto source_super_device =
1234 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1235 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1236 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1237
1238 auto target_super_device =
1239 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1240 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1241 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1242
1243 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1244 *source_builder, source_slot, *target_builder, target_slot, partitions);
1245}
1246
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001247bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1248 // No need to mount metadata for non-Virtual A/B devices.
1249 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1250 return false;
1251 }
1252 // Intentionally not checking |metadata_device_| in Android mode.
1253 // /metadata should always be mounted in Android mode. If it isn't, let caller
1254 // fails when calling into SnapshotManager.
1255 if (!IsRecovery()) {
1256 return true;
1257 }
1258 // In recovery mode, explicitly check |metadata_device_|.
1259 return metadata_device_ != nullptr;
1260}
1261
1262bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1263 // No need to mount metadata for non-Virtual A/B devices.
1264 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1265 return true;
1266 }
1267
1268 if (metadata_device_ == nullptr) {
1269 metadata_device_ = snapshot_->EnsureMetadataMounted();
1270 }
1271 return metadata_device_ != nullptr;
1272}
1273
Kelvin Zhang34618522020-09-28 09:21:02 -04001274std::unique_ptr<android::snapshot::ISnapshotWriter>
1275DynamicPartitionControlAndroid::OpenCowWriter(
1276 const std::string& partition_name,
1277 const std::optional<std::string>& source_path,
1278 bool is_append) {
1279 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1280
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001281 auto super_device = GetSuperDevice();
1282 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001283 return nullptr;
1284 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001285 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001286 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001287 .metadata_slot = target_slot_,
1288 .partition_name = partition_name + suffix,
1289 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001290 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001291 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1292 // it.
1293 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001294} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001295
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001296FileDescriptorPtr DynamicPartitionControlAndroid::OpenCowReader(
1297 const std::string& unsuffixed_partition_name,
1298 const std::optional<std::string>& source_path,
1299 bool is_append) {
1300 auto cow_writer =
1301 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1302 if (cow_writer == nullptr) {
1303 return nullptr;
1304 }
Kelvin Zhangec205cf2020-09-28 13:23:40 -04001305 cow_writer->InitializeAppend(kEndOfInstallLabel);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001306 return cow_writer->OpenReader();
1307}
1308
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001309std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1310 std::string device_dir_str;
1311 if (!GetDeviceDir(&device_dir_str)) {
1312 LOG(ERROR) << "Failed to get device dir!";
1313 return {};
1314 }
1315 base::FilePath device_dir(device_dir_str);
1316 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1317 return super_device;
1318}
1319
1320bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001321 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001322}
1323
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001324bool DynamicPartitionControlAndroid::IsDynamicPartition(
1325 const std::string& partition_name) {
1326 if (dynamic_partition_list_.empty() &&
1327 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1328 CHECK(ListDynamicPartitionsForSlot(source_slot_, &dynamic_partition_list_));
1329 }
1330 return std::find(dynamic_partition_list_.begin(),
1331 dynamic_partition_list_.end(),
1332 partition_name) != dynamic_partition_list_.end();
1333}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001334
Yifan Hong537802d2018-08-15 13:15:42 -07001335} // namespace chromeos_update_engine